﻿using FastReport;
using FastReport.Data;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace Tzw.Common
{
    public class ReportHelper
    {
        public static void Print(DataSet ds,string fileName)
        {
            fileName = $"\\{fileName}.frx";
            var path = Application.StartupPath;

            // 定义报表
            Report report = new FastReport.Report();

            string strDirectory = path + "\\ReportFiles";

            if (!Directory.Exists(strDirectory))
            {
                Directory.CreateDirectory(strDirectory);
            }

            report.Load(strDirectory + fileName);

            report.RegisterData(ds);
            report.Print();
        }

        public static void DesignPort(string fileName, DataSet ds, string dir = "ReportFiles")
        {

            // 获得当前程序的运行路径
            string path = Application.StartupPath;
            // 定义报表
            Report report = new Report();
            string strDirectory = path + $"\\{dir}";
            var file = $"\\{fileName}";

            // 判断文件路径是否存在，不存在则创建文件夹
            if (!Directory.Exists(strDirectory))
            {
                // 不存在就创建目录
                Directory.CreateDirectory(strDirectory);
            }

            // 判断文件是否存在
            if (!File.Exists(strDirectory + file))
            {
                report.FileName = strDirectory + file;
            }
            else
            {
                report.Load(strDirectory + file);
            }

            // 创建报表文件的数据源
            report.RegisterData(ds);

            //给DataBand(明细数据)绑定数据
            DataBand band = report.FindObject("Data1") as DataBand;
            DataSourceBase dataSource = report.GetDataSource(ds.Tables[0].TableName);
            if (band != null) band.DataSource = dataSource;

            // 打开设计界面
            report.Design();
        }
    }

}